package com.itsu.job.controller;

import cn.hutool.core.collection.CollUtil;
import com.itsu.job.config.Job;
import com.itsu.job.config.JobProperties;
import com.itsu.job.context.JobHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Jerry.Su
 * @Date 2021/11/22 15:53
 */
@Deprecated
@RestController
@Slf4j
public class JobController {

    @Autowired
    private JobProperties jobProperties;

    @Autowired
    private JobHelper jobHelper;

    @GetMapping("/stop/{jobId}/{type}")
    public String stop(@PathVariable("jobId") String jobId, @PathVariable("type") Integer type) {
        try {
            jobHelper.stop(jobId, type);
            return "success";
        } catch (Exception e) {
            log.error("stop job error", e);
            return e.getMessage();
        }
    }

    @GetMapping("/schedule/{jobId}")
    public String schedule(@PathVariable("jobId") String jobId) {
        if (!StringUtils.hasText(jobId)) {
            return "not found";
        }
        List<Job> jobs = jobProperties.getJobs().stream().filter(x -> jobId.equals(x.getJobId()))
                .collect(Collectors.toList());
        if (CollUtil.isEmpty(jobs)) {
            return "config job is empty";
        }

        if (JobHelper.scheduleFuture.containsKey(jobId)) {
            return "current jobId:" + jobId + " is already running";
        }

        Job job = jobs.get(0);
        try {
            jobHelper.scheduleJob(job);
            return "success";
        } catch (Exception e) {
            log.error("schedule job error", e);
            return e.getMessage();
        }
    }

    @GetMapping("/run/{jobId}")
    public String runJob(@PathVariable("jobId") String jobId) {
        try {
            jobHelper.runJob(jobId);
            return "success";
        } catch (Exception e) {
            log.error("run job error", e);
            return e.getMessage();
        }
    }

    @GetMapping("/status/{jobId}")
    public int jobStatus(@PathVariable("jobId") String jobId) {
        try {
            Assert.notNull(jobId, "jobId can not be null");
            return jobHelper.status(jobId);
        } catch (Exception e) {
            log.error("find job status error", e);
            return 1;
        }
    }

    @GetMapping("/status")
    public Map<String, Integer> listJobStatus(String jobIdStr) {
       return jobHelper.statusAll(jobIdStr);
    }
}
